<template>
  <div class="mainbody">
    <dv-loading v-show="runFlag" class="loading">Loading...</dv-loading>
    <div class="container">
      <MainTitle :main-title="mainTitle" />
      <div class="button-group">
        <button :class="['system-button', system === 'hcda' ? 'system-button-selected': '']" type="primary" @click="setSystem('hcda')">高压</button>
        <button :class="['system-button', system === 'lcda' ? 'system-button-selected' :'']" type="primary" @click="setSystem('lcda')">低压</button>
      </div>
      <div class="view-frame">
        <div class="elec-trend">
          <div class="elec-trend-title">测试周期选择</div>
        </div>
        <div class="selector">
          <span class="selector-text">测试节点：</span>
          <el-date-picker
            v-model="startDate"
            class="date-style"
            type="date"
            placeholder="选择日期"
          />
          <span class="selector-text"> - </span>
          <el-time-picker
            v-model="startTime"
            class="date-style"
            type="time"
            format="HH:mm"
            placeholder="选择时间"
          />
          <span class="selector-text" style="marginLeft:3rem">测试期时长：</span>
          <el-input-number v-model="hour" class="select" :step="1" step-strictly :min="1" :max="24" />
          <span class="selector-text"> Hour </span>
          <button class="system-button" type="primary" @click="init()">开始测试</button>
        </div>

        <div class="elec-trend">
          <div class="elec-trend-title">测试前后结果对比</div>
        </div>
        <div class="charts">
          <div class="charts-item"><vechart :options="flowOptions" /></div>
          <div class="charts-item"><vechart :options="pressOptions" /></div>
        </div>
        <div class="elec-trend">
          <div class="elec-trend-title">测试结果统计</div>
        </div>
        <div class="statistics">
          <table>
            <tr>
              <th />
              <th>用电量（kWh）</th>
              <th>送气量（m³）</th>
              <th>压力均值（Bar）</th>
              <th>转换效率（m³/kWh）</th>
            </tr>
            <tr>
              <th>测试前</th>
              <td>{{ beforeTest.c }}</td>
              <td>{{ beforeTest.qw }}</td>
              <td>{{ beforeTest.ip }}</td>
              <td>{{ beforeTest.Eta }}</td>
            </tr>
            <tr>
              <th>测试后</th>
              <td>{{ afterTest.c }}</td>
              <td>{{ afterTest.qw }}</td>
              <td>{{ afterTest.ip }}</td>
              <td>{{ afterTest.Eta }}</td>
            </tr>
            <tr class="last-line">
              <td />
              <td><span class="table-text">节约电量： </span><span class="table-value"> {{ saveElec }}</span></td>
              <td />
              <td />
              <td><span class="table-text">转换效率提升百分比：</span><span class="table-value">{{ increasePercent }}%</span></td>
            </tr>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
Object.assign(Date.prototype, {
  switch(time) {
    const date = {
      'yy': this.getFullYear(),
      'MM': this.getMonth() + 1,
      'dd': this.getDate(),
      'hh': this.getHours(),
      'mm': this.getMinutes(),
      'ss': this.getSeconds()
    }
    if (/(y+)/i.test(time)) {
      time = time.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    Object.keys(date).forEach(function(i) {
      if (new RegExp('(' + i + ')').test(time)) {
        if (RegExp.$1.length === 2) {
          date[i] < 10 ? date[i] = '0' + date[i] : date[i]
        }
        time = time.replace(RegExp.$1, date[i])
      }
    })
    return time
  }
})

import { mapState } from 'vuex'
import 'element-ui/lib/theme-chalk/index.css'
import lineOptions from './json/lineOptions.json'
export default {
  components: {
    MainTitle: () => import('@/components/MainTitle.vue'),
    vechart: () => import('@components/charts/Vechart.vue')
  },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      runFlag: false,
      system: 'hcda',
      hour: 1,
      startDate: new Date(),
      startTime: new Date(new Date().getTime() - this.hour * 60 * 60 * 1000),
      lineOptions: lineOptions,
      flowOptions: {},
      pressOptions: {},
      beforeTest: {
        qw: '-',
        ip: '-',
        c: '-',
        Eta: '-'
      },
      afterTest: {
        qw: '-',
        ip: '-',
        c: '-',
        Eta: '-'
      },
      saveElec: '-',
      increasePercent: '-'
    }
  },
  computed: {
    mainTitle() {
      return this.title
    },
    ...mapState({
      service: state => state.service,
      webModel: state => state.authentication.webModel,
      treeTemplate: state => state.component.treeTemplate
    }),
    test_time() {
      const date = this.startDate.switch('yyyy-MM-dd')
      const time = this.startTime.switch('hh:mm:ss')
      return date + ' ' + time
    },
    begin_time() {
      const setdate = new Date(Date.parse(this.test_time.replace(/-/g, '/')))
      const newDate = new Date(setdate.getTime() - this.hour * 60 * 60 * 1000)
      return newDate.switch('yyyy-MM-dd hh:mm:ss')
    },
    end_time() {
      const setdate = new Date(Date.parse(this.test_time.replace(/-/g, '/')))
      const newDate = new Date(setdate.getTime() + this.hour * 60 * 60 * 1000)
      return newDate.switch('yyyy-MM-dd hh:mm:ss')
    }
  },
  created() {
    this.startTime = new Date(new Date().getTime() - this.hour * 60 * 60 * 1000)
    this.getMinuteCdaIcIpData()
    this.getMinuteCdaCIpQwData()
  },
  methods: {
    setSystem(system) {
      this.system = system
      this.init()
    },
    init() {
      this.getMinuteCdaIcIpData()
      this.getMinuteCdaCIpQwData()
    },
    async getMinuteCdaIcIpData() {
      try {
        this.runFlag = true
        // const param = { 'begin_time': '2020-07-15 20:45:15', 'end_time': '2020-07-15 21:45:15', 'tag_id': 'lcda' }
        const param = { 'begin_time': this.begin_time, 'end_time': this.end_time, 'id': this.system }
        const result = await this.service.getMinuteCdaIcIpData(param)
        if (!result.flag || !result.data) {
          this.flowOptions = this.lineOptions
          this.pressOptions = this.lineOptions
          this.$notify({
            title: '暂无数据',
            type: 'error',
            duration: 2500
          })
          return
        }
        const xAxis1 = this.lookup(result.data[0].time, this.test_time).switch('yyyy-MM-dd hh:mm')
        const markLine = {
          'symbol': 'none',
          'data': [
            {
              'silent': false,
              'lineStyle': {
                'type': 'solid',
                'color': 'rgb(255,160,223)'
              },
              'label': {
                'position': 'end',
                'formatter': '测试开始时间' + xAxis1
              },
              'xAxis': xAxis1

            }
          ]
        }
        const min = function(value) {
          return Math.floor(value.min)
        }
        const max = function(value) {
          return Math.ceil(value.max)
        }
        const formatter = function(value, index) {
          return new Date(Date.parse(value)).switch('hh:mm')
        }
        this.flowOptions = { ...this.lineOptions, xAxis: { ...this.lineOptions.xAxis, data: result.data[0].time, axisLabel: { ...this.lineOptions.xAxis.axisLabel, formatter: formatter }}, yAxis: { ...this.lineOptions.yAxis, name: result.data[0].tag_name }, series: [{ ...this.lineOptions.series[0], name: result.data[0].tag_name, data: result.data[0].value, markLine: markLine }] }
        this.pressOptions = { ...this.lineOptions, xAxis: { ...this.lineOptions.xAxis, data: result.data[1].time, axisLabel: { ...this.lineOptions.xAxis.axisLabel, formatter: formatter }}, yAxis: { ...this.lineOptions.yAxis, name: result.data[1].tag_name, min: min, max: max }, series: [{ ...this.lineOptions.series[0], name: result.data[1].tag_name, data: result.data[1].value, markLine: markLine }] }
        this.runFlag = false
      } catch (e) {
        this.$notify({
          title: '请求失败',
          type: 'error',
          duration: 2500
        })
        this.runFlag = false
      }
    },
    async getMinuteCdaCIpQwData() {
      try {
        this.runFlag = true
        // const param1 = { 'begin_time': '2020-07-15 20:45:00', 'end_time': '2020-07-15 21:45:00', 'tag_id': 'lcda' }
        // const param2 = { 'begin_time': '2020-07-15 16:45:00', 'end_time': '2020-07-15 18:45:00', 'tag_id': 'lcda' }
        const param1 = { 'begin_time': this.begin_time, 'end_time': this.test_time, 'id': this.system }
        const param2 = { 'begin_time': this.test_time, 'end_time': this.end_time, 'id': this.system }
        const result1 = await this.service.getMinuteCdaCIpQwData(param1)
        const result2 = await this.service.getMinuteCdaCIpQwData(param2)
        if (!result1.flag && !result2.flag) {
          this.$notify({
            title: '请求失败',
            type: 'error',
            duration: 2500
          })
          this.runFlag = false
          return
        }
        if (!result1.data && !result2.data) {
          this.$notify({
            title: '请求数据为空',
            type: 'error',
            duration: 2500
          })
          this.runFlag = false
          return
        }
        this.beforeTest.qw = result1.data.find(i => i.tag_id === 'qw') && (result1.data.find(i => i.tag_id === 'qw').value || result1.data.find(i => i.tag_id === 'qw').value === 0) ? result1.data.find(i => i.tag_id === 'qw').value.toFixed(2) : '-'
        this.beforeTest.ip = result1.data.find(i => i.tag_id === 'ip') && (result1.data.find(i => i.tag_id === 'ip').value || result1.data.find(i => i.tag_id === 'ip').value === 0) ? result1.data.find(i => i.tag_id === 'ip').value.toFixed(2) : '-'
        this.beforeTest.c = result1.data.find(i => i.tag_id === 'c') && (result1.data.find(i => i.tag_id === 'c').value || result1.data.find(i => i.tag_id === 'c').value === 0) ? result1.data.find(i => i.tag_id === 'c').value.toFixed(2) : '-'
        this.beforeTest.Eta = this.beforeTest.c !== 0 && (this.beforeTest.qw / this.beforeTest.c) ? (this.beforeTest.qw / this.beforeTest.c).toFixed(2) : '-'
        this.afterTest.qw = result2.data.find(i => i.tag_id === 'qw') && (result2.data.find(i => i.tag_id === 'qw').value || result2.data.find(i => i.tag_id === 'qw').value === 0) ? result2.data.find(i => i.tag_id === 'qw').value.toFixed(2) : '-'
        this.afterTest.ip = result2.data.find(i => i.tag_id === 'ip') && (result2.data.find(i => i.tag_id === 'ip').value || result2.data.find(i => i.tag_id === 'ip').value === 0) ? result2.data.find(i => i.tag_id === 'ip').value.toFixed(2) : '-'
        this.afterTest.c = result2.data.find(i => i.tag_id === 'c') && (result2.data.find(i => i.tag_id === 'c').value || result2.data.find(i => i.tag_id === 'c').value === 0) ? result2.data.find(i => i.tag_id === 'c').value.toFixed(2) : '-'
        this.afterTest.Eta = this.afterTest.c !== 0 && (this.afterTest.qw / this.afterTest.c) ? (this.afterTest.qw / this.afterTest.c).toFixed(2) : '-'
        const saveElec = this.beforeTest.c - this.afterTest.c
        this.saveElec = saveElec > 0 ? saveElec.toFixed(2) : 0
        const increasePercent = (this.afterTest.Eta - this.beforeTest.Eta) / this.beforeTest.Eta * 100
        this.increasePercent = increasePercent > 0 ? increasePercent.toFixed(2) : 0
        this.runFlag = false
      } catch (e) {
        this.$notify({
          title: '请求失败',
          type: 'error',
          duration: 2500
        })
        this.runFlag = false
      }
    },
    lookup(array, value) {
      // 将原数组复制，不会影响原数组
      const arr = array.map(item => {
        const time1 = item
        return new Date(Date.parse(time1.replace(/-/g, '/')))
      })
      console.log('arr1', arr)
      const time2 = value
      const i = new Date(Date.parse(time2.replace(/-/g, '/')))
      arr.push(i)
      // 数据排序
      arr.sort((a, b) => {
        return a - b
      })
      console.log('arr2', arr)
      const index = arr.indexOf(i)
      // 当前项在数组第一项 / 最后一项，返回当前项的后一项 / 前一项
      if (index === 0) {
        return arr[index + 1]
      } else if (index === array.length - 1) {
        return arr[index - 1]
      }
      // 当前项和前一项或者后一项比较，返回差值小的项
      const resultIndex =
        arr[index] - arr[index - 1] > arr[index + 1] - arr[index]
          ? index + 1
          : index - 1
      return arr[resultIndex]
    }
  }
}
</script>

<style lang="scss" scopeds>
.loading{
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba($color: #333, $alpha: 0.7);
  z-index: 9;
}
.mainbody{
  height: 100vh;
  background: url('~@assets/report/bg.png') no-repeat;
  background-size: 100% 100%;
}
.container{
  position: relative;
  width: 92%;
  height: 100%;
  margin: 0 auto;
  display: flex;
  flex-flow: column;
}

.view-frame{
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-around;
  height: 85%;
  overflow-y:scroll;
  // margin-top: 1rem;
  // 隐藏滚动条
  &::-webkit-scrollbar {// 兼容Chrome
    display: none;
  }
  &::-o-scrollbar {// 兼容Opera
    display: none;
  }
  scrollbar-width: none;// 兼容Firefox
  -ms-overflow-style: none;// 兼容edge
}
.button-group{
  position: absolute;
  top: 6%;
  right: 0;
    .system-button{
      width: 7rem;
      height: 3.2rem;
      line-height: 3rem;
      color:white;
      align-self: center;
      background-color:transparent;
      border: 1.5px solid rgba(185, 183, 183, 0.5);
      border-radius: 0;
      padding: 0;
      font-size: 1.2rem;
      font-weight: 600;
      margin-left: 2rem;
    }
  }
  .system-button-selected{
    background-color: #00f4ff !important;
    color: #122a7a !important;
  }
  .system-button{
      width: 7rem;
      height: 3.2rem;
      line-height: 3rem;
      color:white;
      align-self: center;
      background-color:transparent;
      border: 1.5px solid rgba(185, 183, 183, 0.5);
      border-radius: 0;
      padding: 0;
      font-size: 1.2rem;
      font-weight: 600;
      margin-left: 2rem;
    }
  .elec-trend{
  height: 3rem;
  border-bottom: 1px solid rgba(185, 183, 183, 0.5);
  margin: 1rem 0;
}
.elec-trend-title{
  font-size: 1.5rem;
  font-style: italic;
  font-weight: 600;
  line-height: 2rem;
}
.selector{
  margin-bottom: 1rem;
}
.selector-text{
  color: #fff;
  font-size: 1.4rem;
  line-height: 3rem;
}
.el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 15rem;
}
.el-input__inner {
  color: #00f4ff !important;
  font-size: 1.2rem;
  font-weight: 600;
  background-color: transparent !important;
  border-radius: 0px;
  border-width: 1px !important;
  border-style: solid !important;
  border-image: initial !important;
  border-color: #aaa !important;
  height: 3rem;
  line-height: 3rem;
}
.el-input__icon{
  height: 3rem;
  line-height: 3rem;
}

.el-input-number__decrease, .el-input-number__increase {
  position: absolute;
  z-index: 1;
  top: 0;
  width: 3rem;
  height: 3rem !important;
  text-align: center;
  background: rgba(170, 170, 170, 0.6);
  color: #fff;
  cursor: pointer;
  font-size: 1.2rem;
  font-weight: 600;
  border: none;
  border-radius: 4px;
}
.el-input-number {
  width: 14rem;
  height: 2rem;
  line-height: 3rem;
}
.el-input-number .el-input {
  display: block;
  position: absolute;
  left: 4rem;
  font-size: 1.2rem;
  display: inline-block;
  width: 40%;
  height: 3rem;
  line-height: 3rem;
}
.el-input-number .el-input__inner {
  padding-left: 0;
  padding-right: 0;
  border-radius: 0;
  background: transparent;
  border: 1px solid #bbb;
  color: #00f4ff;
  font-weight: 600;

}
[class^=el-icon-] {
  font-weight: 600;
}

.charts{
  flex-basis: 35%;
  display: flex;
  justify-content: space-between;
}
.charts-item{
  flex-basis: 49%;
}
.statistics{
  width: 100%;
  flex-basis: 35%;
}
.statistics table{
  width: 100%;
  height: 100%;
  border-radius: 5px;
  background: url('~@assets/report/2bg.png') no-repeat;
  background-size: 100% 100%;
}
.statistics tr{
  height: 25%;
  display: flex;
  border-bottom: 1px solid rgba(185, 183, 183, 0.5);
}
.statistics .last-line{
  border-bottom: none;
}
.statistics td,.statistics th{
  flex: 1;
  text-align: center;
  height: 100%;
  line-height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.statistics td{
  font-size: 1.4rem;
  color: #FFF;
  font-weight: 600;
}
.statistics th{
  font-size: 1.3rem;
  color: #fff;
  font-weight: 500;
}
.table-text{
  font-size: 1.3rem;
  color: #fff;
  font-weight: 500;
}
.table-value{
  font-size: 1.6rem;
  color: #00f4ff ;
  font-weight: 600;
}
</style>
